package org.bing.zion.core;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;


public class ProtocolFilterAdapter implements ProtocolFilter {
	protected static final Log logger = LogFactory.getLog(ProtocolFilter.class);

	public void messageFlush(ProtocolFilterChain chain, Session session, ByteBuffer buf) throws IOException {
	}

	public void sessionClosed(ProtocolFilterChain chain, Session session) throws IOException {
	}

	public void sessionCreated(ProtocolFilterChain chain, Session session) throws IOException {
	}

	public void sessionOpened(ProtocolFilterChain chain, Session session) throws IOException {
	}

	public void messageReceived(ProtocolFilterChain chain, Session session, Object msg) throws IOException {
		chain.next().messageReceived(chain, session, msg);
	}

	public void messageSent(ProtocolFilterChain chain, Session session, Object msg) throws IOException {
		chain.prev().messageSent(chain, session, msg);
	}

	/** IO helper method */
	protected byte[] getBytes(ByteBuffer buf) {
		if (buf.hasArray()) {
			if (buf.limit() == buf.capacity()) {
				return buf.array();
			} else {
				byte[] all = buf.array();
				byte[] res = new byte[buf.limit()];
				System.arraycopy(all, 0, res, 0, res.length);
				return res;
			}
		} else {
			byte[] bs = new byte[buf.limit()];
			buf.get(bs);
			return bs;
		}
	}

	protected int index(byte[] bs, byte t, int offset) {
		for (int i = offset; i < bs.length; i++) {
			byte b = bs[i];
			if (b == t) {
				return i;
			}
		}
		return -1;
	}

}
